package com.shuo.list;

import java.util.Arrays;

/**
 * 栈1的栈底是在数组的始端，栈2的栈底在数组的顶端，两个栈在push元素时候主键朝数组的中间靠拢，
 * 当栈1的栈顶top1+1=栈2 栈顶top2，那么此时栈满
 */
public class ShareStack {
    private Object[] array;
    private int size;
    private int topPtr1;
    private int topPtr2;

    private final static int STACK_1 = 1;

    public ShareStack(int size) {
        this.size = size;
        topPtr1 = -1;
        topPtr2 = size;
        array = new Object[size];
    }

    public void push(Object value, int stackNum) {
        if (isFull())
            throw new RuntimeException("The stack is full");
        if (stackNum == STACK_1) {
            array[++topPtr1] = value;
        } else {
            array[--topPtr2] = value;
        }
    }


    public Object pop(int stackNum) {
        if (isEmpty(stackNum))
            return null;
        if (stackNum == STACK_1) {
            Object value = array[topPtr1];
            array[topPtr1] = null;
            topPtr1--;
            return value;
        } else {
            Object value = array[topPtr2];
            array[topPtr2] = null;
            topPtr2++;
            return value;
        }
    }

    public Object peek(int stackNum) {
        if (isEmpty(stackNum))
            return null;
        if (stackNum == STACK_1) {
            return array[topPtr1];
        } else {
            return array[topPtr2];
        }
    }

    public boolean isEmpty(int stackNum) {
        if (stackNum == STACK_1)
            return topPtr1 == -1;
        else
            return topPtr2 == size;
    }

    public boolean isFull() {
        return topPtr2 <= topPtr1 + 1;
    }

    @Override
    public String toString() {
        return "ShareStack{" +
                "array=" + Arrays.toString(array) +
                '}';
    }

    public static void main(String[] args) {
        ShareStack stack = new ShareStack(4);
        stack.push("1", 1);
        stack.push("2", 1);
        stack.push("3", 1);
        stack.push("11", 2);
        stack.pop(1);
        stack.push("22", 2);
        System.out.println(stack);
    }
}
